package com.itany.ums.util;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * @Author:石小俊
 * @Date: 2022/12/28 15:51
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
public class MyBatisUtil {

    private static SqlSessionFactory factory;
    private static ThreadLocal<SqlSession> local;

    static{
        local = new ThreadLocal<>();
        try {
            factory = new SqlSessionFactoryBuilder()
                    .build(MyBatisUtil
                    .class
                    .getClassLoader()
                    .getResourceAsStream("mybatis-config.xml"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("MyBatis初始化失败");
        }
    }


    public static SqlSession getSession(){
        // 从线程池中获取对应的持久化管理器
        SqlSession session = local.get();
        // 如果没有取到,说明尚未使用
        if(null == session){
            // 从工厂中获取到对应的持久化管理器
            session = factory.openSession();
            // 将获取到的持久化管理器放入到线程池中,便于下次使用
            local.set(session);
        }
        return session;
    }

    public static void close(){
        SqlSession session = local.get();
        if(session != null){
            session.close();
            local.remove();
        }
    }
}
